package com.song.files.controller;


import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.model.Filters;
import com.song.api.BaseController;
import com.song.api.controller.files.FileUploaderControllerApi;
import com.song.exception.GraceException;
import com.song.files.resource.FileResource;
import com.song.files.service.UploaderService;
import com.song.grace.result.GraceJSONResult;
import com.song.grace.result.ResponseStatusEnum;
import com.song.pojo.bo.NewAdminBO;
import com.song.utils.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

@RestController
public class FileUploaderController extends BaseController implements FileUploaderControllerApi {

    @Autowired
    private UploaderService uploaderService;

    @Autowired
    private FileResource fileResource;

    @Autowired
    private GridFSBucket gridFSBucket;

    private static final Logger LOG = LoggerFactory.getLogger(FileUploaderController.class);

    @Override
    public GraceJSONResult uploadFace(String userId, MultipartFile file) throws Exception {

        // 0.判断userId不能为空
        if (StringUtils.isBlank(userId)) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }

        String path = "";
        // 1.开始上传文件，判断file不能为空
        if (file != null) {
            // 获得上传文件的文件名称
            String fileName = file.getOriginalFilename();
            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String[] fileNameArr = fileName.split("\\.");
                // 获得文件后缀
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断文件后缀名是否符合要求
                if (!suffix.equalsIgnoreCase("png") &&
                        !suffix.equalsIgnoreCase("jpg") &&
                        !suffix.equalsIgnoreCase("jpeg")
                ) {
                    return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }
                // 执行上传
//                path = uploaderService.uploadFdfs(file, suffix);
                path = uploaderService.uploadOSS(file, userId, suffix);
            } else {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        // 2.获取完整用户头像路径
        String finalPath = "";
        if (StringUtils.isNotBlank(path)) {
            finalPath = fileResource.getOssHost() + path;
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }

        return GraceJSONResult.ok(finalPath);
    }

    /**
     * 上传多个文件
     *
     * @param userId
     * @param files
     * @return
     * @throws Exception
     */
    @Override
    public GraceJSONResult uploadSomeFiles(String userId, MultipartFile[] files) throws Exception {

        // 声明list,用于存放多个图片的地址路径，返回到前端
        List<String> imageUrlList = new ArrayList<>();
        // 多文件上传必须不为空并且文件数组大于0
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                String path = "";
                // 1.开始上传文件，判断file不能为空
                if (file != null) {
                    // 获得上传文件的文件名称
                    String fileName = file.getOriginalFilename();
                    // 判断文件名不能为空
                    if (StringUtils.isNotBlank(fileName)) {
                        String[] fileNameArr = fileName.split("\\.");
                        // 获得文件后缀
                        String suffix = fileNameArr[fileNameArr.length - 1];
                        // 判断文件后缀名是否符合要求
                        if (!suffix.equalsIgnoreCase("png") &&
                                !suffix.equalsIgnoreCase("jpg") &&
                                !suffix.equalsIgnoreCase("jpeg")
                        ) {
                            continue;
                        }
                        // 执行上传
                        path = uploaderService.uploadOSS(file, userId, suffix);
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }

                LOG.info("path : " + path);
                // 2.获取完整用户头像路径
                String finalPath = "";
                if (StringUtils.isNotBlank(path)) {
                    finalPath = fileResource.getOssHost() + path;
                } else {
                    continue;
                }
                imageUrlList.add(finalPath);
            }
        }
        return GraceJSONResult.ok(imageUrlList);
    }

    /**
     * 文件上传到MongoDB的GridFS中
     *
     * @param newAdminBO
     * @return
     * @throws Exception
     */
    @Override
    public GraceJSONResult uploadToGridFS(NewAdminBO newAdminBO) throws Exception {

        // 判断人脸信息是否为空
        if (StringUtils.isBlank(newAdminBO.getImg64())) {
            GraceException.display(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }

        // base64字符串
        String file64 = newAdminBO.getImg64();

        // 将字符串转 bytes数组
        byte[] bytes = Base64.getDecoder().decode(file64.trim());

        // 转化为输入流
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);

        // 上传到gridFS中
        ObjectId fileId = gridFSBucket.uploadFromStream(newAdminBO.getUsername() + ".png", inputStream);

        // 获取文件中gridFS中的主键id
        String fileIdStr = fileId.toString();

        return GraceJSONResult.ok(fileIdStr);
    }

    /**
     * 从gridFS中读取文件
     *
     * @param faceId
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    public void readInGridFS(String faceId,
                             HttpServletRequest request,
                             HttpServletResponse response) throws Exception {
        // 0.判断参数
        if (StringUtils.isBlank(faceId) || faceId.equalsIgnoreCase("null")) {
            GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }

        // 1.获取内容
        File file = readGridFSByFaceId(faceId);

        // 2.把人脸图片输出到浏览器
        FileUtils.downloadFileByStream(response, file);
    }

    /**
     * 从gridFS中获取文件，并返回base64数据
     *
     * @param faceId
     * @return
     * @throws Exception
     */
    @Override
    public GraceJSONResult readFace64InGridFS(String faceId) {

        // 0.获得gridFS中人脸文件
        File myFile = null;
        try {
            myFile = readGridFSByFaceId(faceId);
        } catch (Exception e) {
            e.printStackTrace();
        }

//        System.out.println(myFile.getAbsolutePath());

        // 1.转换人脸数据为base64
        String base64Face = FileUtils.fileToBase64(myFile);

        return GraceJSONResult.ok(base64Face);
    }


    /**
     * 从GridFS中获取文件
     *
     * @param faceId
     * @return
     */
    private File readGridFSByFaceId(String faceId) throws Exception {
        // 获取内容
        GridFSFindIterable gridFSFindIterable = null;
        try {
            gridFSFindIterable = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));
        } catch (IllegalArgumentException e) {
            GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }
        // 获取内容第一个
        GridFSFile gridFSFile = gridFSFindIterable.first();

        if (gridFSFile == null) {
            GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }

        // 获取文件名
        String fileName = gridFSFile.getFilename();
        LOG.info("filename: " + fileName);

        // 获取文件流，定义存放服务器临时文件位置和名称
//        String tempPath = "/workspaces/temp_face";
        File fileTemp = new File(TEMP_PATH);
        if (!fileTemp.exists()) {
            fileTemp.mkdirs();
        }

        File myFile = new File(TEMP_PATH + "/" + fileName);

        // 创建输出流
        OutputStream os = new FileOutputStream(myFile);
        // 执行下载，下载到本地磁盘，管理员头像不多，下载到服务器不会占用大量硬盘空间
        gridFSBucket.downloadToStream(new ObjectId(faceId), os);

        return myFile;
    }

}
